<script setup lang="ts">
defineOptions({
  name: "User",
  inheritAttrs: false,
});

import {
  getResoucesImgPage,
  saveResourcesImg,
  deleteResourcesImg,
} from "@/api/auth";
import { getDeptOptions } from "@/api/dept";
import { getRoleOptions } from "@/api/role";

import MultiUpload from "@/components/Upload/MultiUpload.vue";

import { ResourcesForm, ResouceQuery, AuthPageVO } from "@/api/auth/types";

import type { UploadInstance } from "element-plus";
import { genFileId } from "element-plus";

const queryFormRef = ref(ElForm); // 查询表单
const resourcesFormRef = ref(ElForm); // 用户表单
const uploadRef = ref<UploadInstance>(); // 上传组件

const loading = ref(false); //  加载状态
const removeIds = ref([]); // 删除用户ID集合 用于批量删除
const queryParams = reactive<ResouceQuery>({
  pageNum: 1,
  pageSize: 10,
  type: "",
});
const dateTimeRange = ref("");
const total = ref(0); // 数据总数
const pageData = ref<AuthPageVO[]>(); // 用户分页数据
const deptList = ref<OptionType[]>(); // 部门下拉数据源
const roleList = ref<OptionType[]>(); // 角色下拉数据源
const listData = ref([""]);
const showViewer = ref(false);

function getImg(imgUrl: any) {
  listData.value = [];
  listData.value.push(imgUrl);
  showViewer.value = true;
}

function closeViewer() {
  showViewer.value = false;
}

const logicImageList = ref([]);

watch(dateTimeRange, (newVal) => {
  if (newVal) {
    queryParams.startTime = newVal[0];
    queryParams.endTime = newVal[1];
  } else {
    queryParams.startTime = "";
    queryParams.endTime = "";
  }
});

// 弹窗对象
const dialog = reactive({
  visible: false,
  type: "user-form",
  width: 800,
  title: "",
});

// 用户表单数据
const formData = reactive<ResourcesForm>({
  resourcesId: "",
  status: "0",
  remark: "",
});

// 用户导入数据
const importData = reactive({
  deptId: undefined,
  file: undefined,
  fileList: [],
});

// 校验规则
const rules = reactive({
  status: [{ required: true, message: "请选择认证状态", trigger: "blur" }],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  getResoucesImgPage(queryParams)
    .then(({ data }) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  dateTimeRange.value = "";
  queryParams.pageNum = 1;
  queryParams.startTime = undefined;
  queryParams.endTime = undefined;
  handleQuery();
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 加载角色下拉数据源 */
async function loadRoleOptions() {
  getRoleOptions().then((response) => {
    roleList.value = response.data;
  });
}

/** 加载部门下拉数据源 */
async function loadDeptOptions() {
  getDeptOptions().then((response) => {
    deptList.value = response.data;
  });
}

async function openDialog(type: string, row?: any) {
  dialog.visible = true;
  dialog.type = type;
  formData.imgList = [];
  // 用户表单弹窗
  await loadDeptOptions();
  await loadRoleOptions();
  if (row != undefined) {
    dialog.title = "审核";

    Object.assign(formData, { ...row });
  }
}

/**
 * 关闭弹窗
 * @param type 弹窗类型  用户表单：user-form | 用户导入：user-import
 */
function closeDialog() {
  dialog.visible = false;
  if (dialog.type === "user-form") {
    resourcesFormRef.value.resetFields();
    resourcesFormRef.value.clearValidate();

    formData.resourcesId = undefined;
    formData.status = "1";
  } else if (dialog.type === "user-import") {
    importData.file = undefined;
    importData.fileList = [];
  }
}

/** 删除用户 */
function handleDelete(id?: number) {
  const resourcesIds = [id || removeIds.value].join(",");
  if (!resourcesIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除认证?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deleteResourcesImg(resourcesIds).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  resourcesFormRef.value.validate((valid: any) => {
    if (valid) {
      const resourcesId = formData.resourcesId;
      loading.value = true;
      saveResourcesImg(formData)
        .then(() => {
          ElMessage.success("图片成功");
          closeDialog();
          resetQuery();
        })
        .finally(() => (loading.value = false));
    }
  });
}, 3000);

onMounted(() => {
  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 部门树
      <el-col :lg="4" :xs="24" class="mb-[12px]">
        <dept-tree v-model="queryParams.deptId" @node-click="handleQuery" />
      </el-col> -->

      <!-- 用户列表 -->
      <el-col :lg="24" :xs="24">
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="创建时间">
              <el-date-picker
                class="!w-[240px]"
                v-model="dateTimeRange"
                type="daterange"
                range-separator="~"
                start-placeholder="开始时间"
                end-placeholder="截止时间"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleQuery"
                ><i-ep-search />搜索</el-button
              >
              <el-button @click="resetQuery">
                <i-ep-refresh />
                重置</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <el-image-viewer
          v-if="showViewer"
          :z-index="10000"
          @close="closeViewer"
          :url-list="listData"
        />
        <el-card shadow="never" class="table-container">
          <template #header>
            <div class="flex justify-between">
              <div>
                <el-button
                  v-hasPerm="['sys:user:add']"
                  type="success"
                  @click="openDialog('user-form')"
                  ><i-ep-plus />新增</el-button
                >
                <el-button
                  v-hasPerm="['sys:user:delete']"
                  type="danger"
                  :disabled="removeIds.length === 0"
                  @click="handleDelete()"
                  ><i-ep-delete />删除</el-button
                >
              </div>
            </div>
          </template>

          <el-table
            v-loading="loading"
            :data="pageData"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column
              align="center"
              label="序号"
              type="index"
              width="150"
            />
            <el-table-column
              label="图片"
              align="center"
              prop="resouceImg"
              width="120"
            >
              <template #default="scope">
                <span
                  ><img
                    :src="scope.row.resouceImg"
                    style="height: 60px"
                    @click="getImg(scope.row.resouceImg)"
                /></span>
              </template>
            </el-table-column>

            <el-table-column
              label="上传时间"
              align="center"
              prop="createDate"
            />

            <!-- <el-table-column label="操作" align="center">
              <template #default="scope">
                <el-button
                  v-hasPerm="['sys:user:edit']"
                  type="primary"
                  link
                  size="small"
                  @click="openDialog('user-form', scope.row)"
                  ><i-ep-edit />删除</el-button
                >
              </template> -->
            <!-- </el-table-column> -->
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      @close="closeDialog"
    >
      <!-- 用户新增/编辑表单 -->
      <el-form
        v-if="dialog.type === 'user-form'"
        ref="resourcesFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="图片上传">
          <multi-upload v-model="formData.imgList" />
        </el-form-item>
      </el-form>

      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 认</el-button>
          <el-button @click="dialog.visible = false">返 回</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
